package com.mysiteforme.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;
import com.mysiteforme.admin.dao.ElectricityHeadlinesUserDao;
import com.mysiteforme.admin.entity.ElectricityClassify;
import com.mysiteforme.admin.entity.ElectricityHeadlines;
import com.mysiteforme.admin.entity.ElectricityHeadlinesUser;
import com.mysiteforme.admin.entity.Menu;
import com.mysiteforme.admin.service.ElectricityClassifyService;
import com.mysiteforme.admin.service.ElectricityHeadlinesService;
import com.mysiteforme.admin.service.ElectricityHeadlinesUserService;
import com.xiaoleilu.hutool.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import com.mysiteforme.admin.annotation.SysLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.script.AbstractScriptEngine;
import javax.servlet.ServletRequest;
import javax.swing.text.AbstractDocument;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 平台头条  前端控制器
 * </p>
 *
 * @author wangl
 * @since 2019-09-20
// */
@Controller
@RequestMapping("/admin/electricityHeadlines")
public class ElectricityHeadlinesController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ElectricityHeadlinesController.class);

    @Autowired
    private ElectricityHeadlinesService electricityHeadlinesService;
    @Autowired
    private ElectricityClassifyService electricityClassifyService;
    @Autowired
    private ElectricityHeadlinesUserService electricityHeadlinesUserService;

    @GetMapping("list")
    @SysLog("跳转平台头条列表")
    public String list(){
        return "/admin/electricityHeadlines/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求平台头条列表数据")
    public LayerData<ElectricityHeadlines> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                                @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                                ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        LayerData<ElectricityHeadlines> layerData = new LayerData<>();
        EntityWrapper<ElectricityHeadlines> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag",false);
        wrapper.orderBy("create_date",false );
        if(!map.isEmpty()){
            String title = (String) map.get("title");
            if(StringUtils.isNotBlank(title)) {
                wrapper.like("title",title);
            }else{
                map.remove("title");
            }


            String beginCreatDate = (String) map.get("beginCreatDate");
            String endCreatDate = (String) map.get("endCreatDate");

            if(StringUtils.isNotBlank(beginCreatDate)) {
                Date begin = DateUtil.parse(beginCreatDate);
                wrapper.ge("create_date",begin);
            }else{
                map.remove("beginCreatDate");
            }
            if(StringUtils.isNotBlank(endCreatDate)) {
                String endstr = endCreatDate.substring(0,10)+" 23:59:59";
                Date end = DateUtil.parse(endstr);
                wrapper.le("create_date",end);
            }else{
                map.remove("endCreatDate");
            }

        }
        Page<ElectricityHeadlines> pageData = electricityHeadlinesService.selectPage(new Page<>(page,limit),wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @GetMapping("add")
    @SysLog("跳转新增平台头条页面")
    public String add(Model model){
        Map<String,Object> map = Maps.newHashMap();
        map.put("parentId",null);
        map.put("isShow",false);
        List<ElectricityClassify> classifyList = electricityClassifyService.selectAllClassify(map);
        model.addAttribute("classifyList",classifyList);
        return "/admin/electricityHeadlines/add";
    }

    @PostMapping("add")
    @SysLog("保存新增平台头条数据")
    @ResponseBody
    public RestResponse add(@RequestBody ElectricityHeadlines electricityHeadlines){
        electricityHeadlinesService.save(electricityHeadlines);
        return RestResponse.success();
    }

    @GetMapping("edit")
    @SysLog("跳转编辑平台头条页面")
    public String edit(Long id,Model model){
        ElectricityHeadlines electricityHeadlines = electricityHeadlinesService.getById(id);

        List<Long> classifyIds = Lists.newArrayList();
        if(electricityHeadlines != null) {
            Set<ElectricityClassify> classifySet = electricityHeadlines.getClassifySet();
            if (classifySet != null && classifySet.size() > 0) {
                for (ElectricityClassify m : classifySet) {
                    classifyIds.add(m.getId());
                }
            }
        }
        Map<String,Object> map = com.google.common.collect.Maps.newHashMap();
        map.put("parentId",null);
        map.put("isShow",false);
        List<ElectricityClassify> classifyList = electricityClassifyService.selectAllClassify(map);
        model.addAttribute("classifyList",classifyList);
        model.addAttribute("classifyIds",classifyIds);
        model.addAttribute("electricityHeadlines",electricityHeadlines);
        return "/admin/electricityHeadlines/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑平台头条数据")
    public RestResponse edit(@RequestBody ElectricityHeadlines electricityHeadlines){
        if(null == electricityHeadlines.getId() || 0 == electricityHeadlines.getId()){
            return RestResponse.failure("ID不能为空");
        }

        ElectricityHeadlines headlines = electricityHeadlinesService.getById(electricityHeadlines.getId());
        if(!headlines.getTitle().equals(electricityHeadlines.getTitle())){
            if(electricityHeadlinesService.getCount(electricityHeadlines.getTitle())>0){
                return RestResponse.failure("角色名称已存在");
            }
        }
        electricityHeadlinesService.updateHeadlines(electricityHeadlines);
        return RestResponse.success();
    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除平台头条数据")
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(null == id || 0 == id){
            return RestResponse.failure("ID不能为空");
        }
        ElectricityHeadlines electricityHeadlines = electricityHeadlinesService.selectById(id);
        electricityHeadlines.setDelFlag(true);
        electricityHeadlinesService.updateById(electricityHeadlines);
        //删除用户中间表
        EntityWrapper<ElectricityHeadlinesUser> userWrapper = new EntityWrapper<ElectricityHeadlinesUser>();
        userWrapper.eq("headlines_id",id);
        electricityHeadlinesUserService.delete(userWrapper);
        return RestResponse.success();
    }

}